import 'dart:io';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_project/config/loading_toast.dart';
import '../../config/app_bar_view.dart';
import '../../config/theme_color.dart';
import 'package:flutter_mailer/flutter_mailer.dart';

class UserFeedBackPage extends StatelessWidget {
  final String title;

  UserFeedBackPage({this.title = '', super.key});

  final TextEditingController _feedbackController = TextEditingController();
  final TextEditingController _telController = TextEditingController();
  final FocusNode feedFocusNode = FocusNode();
  final FocusNode telFocusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return CommonAppWidget.navAppBar(
      title: title,
      rightActions: [
        Container(
          margin: const EdgeInsets.only(right: 0, top: 10, bottom: 10),
          height: 31,
          child: TextButton(
            child: const Icon(Icons.send_rounded),
            onPressed: () {
              _getFeedBack(context);
            },
          ),
        )
      ],
      childWidget: GestureDetector(
        onTap: () {
          cancelKeyBoard();
        },
        child: Container(
            color: ThemeColor.mainBgColor,
            padding: const EdgeInsets.fromLTRB(15, 5, 15, 0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const SizedBox(
                  height: 10,
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    RichText(
                      text: const TextSpan(
                        text: '*',
                        style: TextStyle(color: Colors.red),
                        children: [
                          TextSpan(
                            text: '必填',
                            style: TextStyle(color: Colors.black),
                          ),
                        ],
                      ),
                    ),
                    TextButton(
                      style: TextButton.styleFrom(
                          padding: EdgeInsets.zero,
                          minimumSize: Size.zero,
                          tapTargetSize: MaterialTapTargetSize.shrinkWrap),
                      onPressed: () {
                        String textStr = _feedbackController.text;
                        if (textStr.isEmpty) {
                          toast('请输入内容');
                          return;
                        }
                        if (textStr.isNotEmpty) {
                          _feedbackController.clear();
                        }
                      },
                      child: const Text(
                        '清空',
                        style: TextStyle(
                            fontWeight: FontWeight.w500, color: Colors.red),
                      ),
                    )
                  ],
                ),
                const SizedBox(
                  height: 10,
                ),
                Container(
                  color: Colors.white,
                  height: 180,
                  child: TextField(
                    focusNode: feedFocusNode,
                    controller: _feedbackController,
                    maxLength: 100,
                    maxLines: 8,
                    minLines: 6,
                    // scrollPadding: const EdgeInsets.only(right: 5),
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.black,
                    ),
                    decoration: InputDecoration(
                      hintStyle: TextStyle(color: ThemeColor.textColorSecond),
                      hintText: "请输入您的宝贵意见",
                      border: InputBorder.none,
                      contentPadding:
                          const EdgeInsets.only(left: 10, top: 10, right: 10),
                      // contentPadding: EdgeInsets.all(20),
                    ),
                  ),
                ),
                const SizedBox(
                  height: 10,
                ),
                const Text('选填'),
                const SizedBox(
                  height: 10,
                ),
                Container(
                  alignment: Alignment.center,
                  color: Colors.white,
                  height: 50,
                  child: TextField(
                    focusNode: telFocusNode,
                    controller: _telController,
                    keyboardType: TextInputType.phone,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.black,
                    ),
                    decoration: InputDecoration(
                      hintText: "请输入您的联系方式",
                      hintStyle: TextStyle(
                          fontSize: 14, color: ThemeColor.textColorSecond),
                      border: InputBorder.none,
                      contentPadding: const EdgeInsets.only(left: 10),
                    ),
                  ),
                )
              ],
            )),
      ),
    );
  }

  // 意见反馈
  _getFeedBack(BuildContext context) async {
    if (_feedbackController.text.isEmpty) {
      toast('请输入您的宝贵意见');
      return false;
    }

    //取消键盘响应
    cancelKeyBoard();
    sendMail(context);
  }

  //取消键盘响应
  cancelKeyBoard() {
    if (feedFocusNode.hasFocus) {
      feedFocusNode.unfocus();
    }

    if (telFocusNode.hasFocus) {
      telFocusNode.unfocus();
    }
  }

  Future<void> sendMail(BuildContext context) async {
    final bool canSend = await FlutterMailer.canSendMail();
    if (Platform.isIOS) {
      if (!canSend) {
        toast('请安装邮箱客户端');
        return;
      }
    }

    String emailStr = 'APP用户反馈';
    final MailOptions mailOptions = MailOptions(
      body: _feedbackController.text,
      subject: '$emailStr:${_telController.text}',
      recipients: <String>[
        'chenzhiliang@aishi.ai',
      ],
      isHTML: true,
      // bccRecipients: ['other@example.com'],
      ccRecipients: <String>['754537750@qq.com'],
    );

    String platformResponse = '';
    try {
      final MailerResponse response = await FlutterMailer.send(mailOptions);
      switch (response) {
        case MailerResponse.saved:
          platformResponse = 'mail was saved to draft';
          break;
        case MailerResponse.sent:
          platformResponse = 'mail was sent';
          break;
        case MailerResponse.cancelled:
          platformResponse = 'mail was cancelled';
          break;
        case MailerResponse.android:
          platformResponse = 'intent was success';
          debugPrint('已经发送完邮件了');
          break;
        default:
          platformResponse = 'unknown';
          break;
      }
    } on PlatformException catch (error) {
      platformResponse = error.toString();
      debugPrint(platformResponse);
    } catch (error) {
      platformResponse = error.toString();
    }
  }
}
